﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace Mozlite.Cryptography
{
    /// <summary>
    /// 对称加密算法的解密对象。
    /// </summary>
    public class Decryptor
    {
        /// <summary>
        /// 初始化类<see cref="T:Decryptor"/>。
        /// </summary>
        /// <param name="algorithm">加密算法类型<see cref="T:Mozlite.Cryptography.EncryptionAlgorithm"/>。</param>
        public Decryptor(EncryptionAlgorithm algorithm)
        {
            transformer = new DecryptTransformer(algorithm);
        }

        private DecryptTransformer transformer;
        private byte[] iv;
        /// <summary>
        /// 解密数据。
        /// </summary>
        /// <param name="data">需要解密的数据。</param>
        /// <param name="key">解密钥匙。</param>
        /// <returns>返回解密后的数据。</returns>
        public byte[] Decrypt(byte[] data, byte[] key)
        {
            //为解密数据设置内存流。
            MemoryStream ms = new MemoryStream();

            //传递初始化向量。
            transformer.IV = iv;
            ICryptoTransform transform = transformer.GetCryptoServiceProvider (key);
            CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
            try
            {
                cs.Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                throw new Exception("将加密数据写入流时出错： \n" + ex.Message);
            }
            cs.FlushFinalBlock();
            cs.Close();
            // 发送回数据。
            return ms.ToArray();
        } 
        /// <summary>
        /// 设置初始化向量。
        /// </summary>
        public byte[] IV
        {
            set { iv = value; }
        }
    }
}
